from sqlalchemy import engine_from_config

from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid_mailer import mailer_factory_from_settings
from pyramid.session import UnencryptedCookieSessionFactoryConfig

from .security import groupfinder

from .models import (
    Base,
    DBSession,
    )

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    # configure database connection
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    # configure authentication policy
    authn_policy = AuthTktAuthenticationPolicy('Du6yee4e',
                                                callback=groupfinder,
                                                hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()

    config = Configurator(settings=settings,
                          root_factory='monaem.models.RootFactory')
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    session_factory = UnencryptedCookieSessionFactoryConfig('Ty6sIUe9')
    config.set_session_factory(session_factory)

    mailer_factory_from_settings(settings)

    config.add_static_view('static', 'monaem:static', cache_max_age=3600)
    config.add_static_view('news', 'monaem:news', cache_max_age=3600)

    # define routes
    config.add_route('home', '/')
    config.add_route('carnet_rdv', '/carnet_rdv')
    config.add_route('change_details', '/changer_coordonnees')
    config.add_route('change_password', '/changer_mot_de_passe')
    config.add_route('date_examen', '/date_examen')
    config.add_route('dates_stage', '/dates_stage')
    config.add_route('email_password', '/email_password')
    config.add_route('extrait_compte', '/extrait_compte')
    config.add_route('faq_cgv', '/faq_cgv')
    config.add_route('faq_mentions_legales', '/faq_mentions_legales')
    config.add_route('faq_pieces_a_presenter', '/faq_pieces_a_presenter')
    config.add_route('fiche_inscription', '/fiche_inscription')
    config.add_route('last_connected', '/last_connected')
    config.add_route('login', '/login')
    config.add_route('login_as', '/login_as/{login}')
    config.add_route('logout', '/logout')
    config.add_route('member_search', '/member_search')
    config.add_route('member_page', '/member_page/{member_id}')
    config.add_route('reglement', '/reglement')

    config.scan()
    return config.make_wsgi_app()

